<?php
/*
	BLOBIR (BLOB Image Resizer)
	
	Copyright © 2010 Kevin Jantzer
	
	Version 1.0
	
	Latest version and additional information available at:
		http://blobir.googlecode.com/


	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
	
	--
	ABOUT:
	This file extracts BLOB content (img) from a DB table,
	resizes it based on URL parameters, sharpens it, and then 
	displays the image.
	
	--
	USAGE:
	To use this script, add the following paramters after
	the URL to this page
		- Width = w	
		- Height = h
		- Sharpen = s	(optional)
		- Photo ID = last number
		
		example:
			<img src="blobir.php/w512:h512:s7/179" alt="Don't forget your alt" />
	
	--
	DATABASE STRUCTURE:		
	Create your image table with the following code:
		CREATE TABLE my_image_table (
			id INT NOT NULL AUTO_INCREMENT,
			name VARCHAR(30) NOT NULL,
			type VARCHAR(30) NOT NULL,
			size INT NOT NULL,
			content MEDIUMBLOB NOT NULL,
		PRIMARY KEY(id)
		);
	
	
	@author Kevin Jantzer, Folium Partners LLC.
	@date Oct 12, 2010 - REVISION 2

	@todo Add images for Errors
	@todo Allow for URL to contain only photo ID
	@todo Create default height and width if not specified in URL


	PUBLIC VARS
*/
	// DB settings
	$dbhost = '';
	$dbuser = '';
	$dbpass = '';
	$dbname = '';
	$dbtable = '';
	


/* ******************************************************************************************************
	END PUBLIC VARS
	change code below at your own risk
****************************************************************************************************** */

$db = new mysqli("$dbhost", "$dbuser", "$dbpass", "$dbname");

// set up query string
$query = "SELECT name, type, size, content FROM $dbtable WHERE id="; 


/*
	Parameters form URL
	
	Format:		"view_headshot.php/wWIDTH:hHEIGHT/ID"
	Example:	"view_headshot.php/w200:h200:s7/185"
*/
$parameters = explode("/",end(explode(".php", $_SERVER['PHP_SELF'])));

	// get the photo ID
	$id = $parameters[2];
	
	// get the desired Width and Height
	list($width,$height,$sharpen_amt) = explode(":",$parameters[1]);
	$thumbnail_width = substr($width,1);
	$thumbnail_height = substr($height,1);
	$sharpen_amt = substr($sharpen_amt,1);
		if($sharpen_amt == "") $sharpen_amt = 7;


/*
	If we have all 3 parameters...
	
	we must have a specified width, height, and photo ID
	in order to continue
*/
if($thumbnail_width > 0 && $thumbnail_height > 0 && is_numeric($id)):

	$result = $db->query($query."'$id'") or die('Error, query failed');
	
	
	/*
		if we have a successful query
		
		meaning the photo ID exists in the DB, then we 
		contiune the process.
	*/
	if($result->num_rows > 0):
	
		// list the content from the DB
		list($name, $type, $size, $content) = $result->fetch_array();
	
		// create an image from the DB BLOB
		$myImage = imagecreatefromstring($content);
		
	    // get the width and height of the original BLOB image
	    $width_orig = imagesx($myImage);
		$height_orig = imagesy($myImage);
	    
		// get the ration of the the original BLOB image
	    $ratio_orig = $width_orig/$height_orig;
	   
		// determine the new width and height of the new image
	    if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
	       $new_height = $thumbnail_width/$ratio_orig;
	       $new_width = $thumbnail_width;
	    } else {
	       $new_width = $thumbnail_height*$ratio_orig;
	       $new_height = $thumbnail_height;
	    }
		
	    $x_mid = $new_width/2;  //horizontal middle
	    $y_mid = $new_height/2; //vertical middle
	   
	    $process = imagecreatetruecolor(round($new_width), round($new_height));
	    imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
	    
	    $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
	    imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
		
		
		/*
			Sharpen the Image
			
			the next three steps will sharpen the image.
			
		*/
		// define the sharpen matrix
		$sharpen = array(
			array(0.0, -1.0, 0.0),
			array(-1.0, $sharpen_amt, -1.0), // the middle number sharpens the image. 5=really sharp, 10=semi-sharp
			array(0.0, -1.0, 0.0)
		);
		
		// calculate the sharpen divisor
		$divisor = array_sum(array_map('array_sum', $sharpen));
		
		// apply the matrix
		imageconvolution($thumb, $sharpen, $divisor, 0);

		
		header('Content-type: image/jpeg');
		
		
		// display the image based on the type ($type comes form the DB)
		switch($type){
			case "image/jpeg":
				imagejpeg($thumb, null, 100);
				break;
			case "image/png":
				imagepng($thumb, null, 100);
				break;
			case "image/gif":
				imagegif($thumb, null, 100);
				break;
		}
		
	
	else:
		
		// given photo ID does not exist in the DB
	
	endif;

else:

	// parameters not correctly specified
	// we need to create a picture from text

endif;
 
 
?>
